package map.tile.server.controller;


import map.tile.server.dto.TileIndex;
import map.tile.server.po.R;
import map.tile.server.service.BaseTileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping(value = "/api/v1/vector")
public class TileController {

    @Autowired
    BaseTileService baseTileService;


    @GetMapping("/{collectionName}/{z}/{x}/{y}.pbf")
    public void test(@PathVariable String collectionName, @PathVariable Integer z, @PathVariable Integer x, @PathVariable Integer y, HttpServletResponse response) {
        // 清空response
        response.reset();
        // 设置response的Header
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

        response.setContentType("application/x-protobuf");

        try {
            byte[] data = baseTileService.getTile(new TileIndex(z, x, y, collectionName));
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(y + ".pbf", "UTF-8"));
            response.addHeader("Content-Length", "" + data.length);
            System.out.println(data.length);
            System.out.println("长度");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(data);
            outputStream.flush();
            System.out.println("下载完成");

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            e.printStackTrace();
        }


    }

    @GetMapping("/tile")
    public R test(@RequestParam String collectionName) {

        try {
            baseTileService.TileTable(collectionName, 9, 18);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }


    }
}
